package com.hzdl.car.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzdl.car.bean.Role;
import com.hzdl.car.bean.User;
import com.hzdl.car.mapper.RoleMapper;
import com.hzdl.car.mapper.UserMapper;
import com.hzdl.car.service.UserService;
import com.hzdl.car.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceimpl implements UserService {

    @Autowired
    private UserMapper mapper;

    @Autowired
    private RoleMapper roleMapper;
    @Override
    public PageInfo<User> findAll(UserVo userVo) {
        PageHelper.startPage(userVo.getPage(),userVo.getLimit());
        List<User> list = mapper.findAll(userVo);
        return new  PageInfo(list);
    }

    @Override
    public int add(UserVo userVo) {
        return mapper.add(userVo);
    }

    @Override
    public int update(UserVo userVo) {
        return mapper.update(userVo);
    }

    @Override
    public int delete(Integer userid) {
        return mapper.delete(userid);
    }

    @Override
    public User findByid(Integer userid) {
        return mapper.findByid(userid);
    }

    @Override
    public User login(User user) {
        return mapper.login(user);
    }

    @Override
    public List<Map<String, Object>> findAll1(UserVo userVo) {
        List<Role> all = roleMapper.findAll();
        List<Role> uList = roleMapper.findByUid(userVo.getUserid());

        List<Map<String ,Object> > list =  new ArrayList<>();
        for (Role role : all){

            Boolean checked = false;
            for (Role role1: uList){
                if(role.getRoleid() == role1.getRoleid()){
                    // 当前用户有这个角色
                    checked = true;
                    break;
                }
            }
            Map<String ,Object> map = new HashMap<>();
            map.put("LAY_CHECKED",checked);
            map.put("roleid",role.getRoleid());
            map.put("rolename",role.getRolename());
            map.put("roledesc",role.getRoledesc());
            list.add(map);

        }

        return list;
    }

    @Override
    public int updateUserRole(UserVo userVo,Integer [] ids) {
        int i = roleMapper.deleteUserRoleByUid(userVo.getUserid());
        int row=0;

        for (Integer rid : ids){
            row += roleMapper.insertUserRole(userVo.getUserid() , rid);
        }

        return row;
    }

    @Override
    public int resetPwd(Integer userid) {
        return mapper.resetPwd(userid);
    }
}
